package com.bzgwl.mybatis_plus.security;

import com.bzgwl.mybatis_plus.sys.mapper.PermissionMapper;
import com.bzgwl.mybatis_plus.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * Author: Professor_Kong
 * date: 2018/3/22
 */
@Component
@SuppressWarnings("all")
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
//    @Qualifier("myUserDetailsService")
    private UserDetailsService myUserDetailsService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        UserDetails user = myUserDetailsService.loadUserByUsername(username);
        if(user == null){
            throw new BadCredentialsException("用户没有找到");
        }

        //加密过程在这里体现
        if (!password.equals(user.getPassword())) {
            System.out.print("密码错误");
            throw new BadCredentialsException("密码错误");
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();

        //获取当前用户
        return new UsernamePasswordAuthenticationToken(user, user.getPassword(), authorities);
    }

    public boolean supports(Class<?> var1){
        return true;
    }
}
